home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2082 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: ukcc.uky.edu!JJSTEP00
  2. From: JJSTEP00@ukcc.uky.edu (Jason Stephenson)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: pseudo-random numbers
  5. Date: Thu, 18 Jan 96 18:29:55 EST
  6. Organization: The University of Kentucky
  7. Message-ID: <1771210427S86.JJSTEP00@ukcc.uky.edu>
  8. References: <17709D420S86.JJSTEP00@ukcc.uky.edu> <4d3ijv$9fl@news.iag.net> <DLE110.Ixp@thinkage.on.ca>
  9. NNTP-Posting-Host: ukcc.uky.edu
  10.  
  11. In article <DLE110.Ixp@thinkage.on.ca>
  12. atbowler@thinkage.on.ca (Alan Bowler) writes:
  13.  
  14. >
  15. >In article <4d3ijv$9fl@news.iag.net> jatmon@iag.net (John R Buchan) writes:
  16. >>
  17. >>One solution, suggested in the faq <polite jab>, is:
  18. >>
  19. >>   (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  20. >
  21. >Minor point.  You have a typo.  That should be
  22. >    (int)((double)rand() / ((double)RAND_MAX + 1) / N)
  23.  
  24. Actually, that's not a typo.  I asked the original question before reading
  25. a recent version of the FAQ.  (The copy I had was several months old.)
  26.  
  27. The code above should be:
  28.  
  29.      (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  30.  
  31. rand() / (RAND_MAX + 1) will give a value between 0 and 1 when cast as a
  32. double.  One then multiplies by the integer N to get a value between 0 and
  33. N - 1.  (Now, I just have to make this work with Random() on the Macintosh
  34. which returns a signed short int and has no definition for RAND_MAX....Aw,
  35. it won't be hard.)
  36.  
  37. My original question was why I seemed to get better results with a method that
  38. the FAQ does not recommend than the results I got with the recommended method.
  39. The answer, in a nut shell, was that I was not casting the values as above and
  40. was always getting a value of 0.  Anyway, this subject has been beaten to
  41. death in this newsgroup and in e-mail.  I promise to refrain from asking any
  42. more questions on this topic, until someone comes up with a way for a computer
  43. to get truly random integers (without attaching a roulette wheel).
  44.  
  45. +----------------------------+-----------------------------+
  46. |     Jason Stephenson       | "Curiouser and curiouser,"  |
  47. |   jjstep00@ukcc.uky.edu    |        said Alice.          |
  48. +----------------------------+-----------------------------+
  49.